/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28 
 */
package com.tzinfo.tzb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.ForumRecommend;
import com.tzinfo.tzb.domain.ForumRecommend.ForumRecommendData;
import com.tzinfo.tzb.util.TzbCommonData;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.util.ResFinder;

public class TzbMyShoucangActivity extends TzbBaseActivity implements
		IXListViewListener {
	// 标志

	// 参数

	// 适配器
	private ImageAdapter imageAdapter;

	// 数据
	private List<Map<String, Object>> data;
	private ForumRecommend forumRecommend;

	// UI组件
	private YXWXListView listView;
	private RelativeLayout layout_no_listdata;

	// 其他
	private Handler mHandler;
	public static TzbMyShoucangActivity activity;
	private int page = 1; // 页码
	private int pagesize = 15; // 每页条数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		activity = this;
		setContentView(ResFinder.getR(this, "R.layout.tzb_ac_main_my_shoucang"));
		initParameter();
		initAnimation();
		initUI();
		initData();
		listView.setSelection(0);
		// listView.post(new Runnable() {
		// @Override
		// public void run() {
		// listView.smoothScrollToPosition(TzbDynamicData.POSITION);
		// }
		// });
	}

	private void initParameter() {
		// Intent thisIntent = this.getIntent();
		// classSubMenu = (ClassSubMenu) thisIntent
		// .getSerializableExtra("classSubMenu");
		// classSubMenu = TzbCommonData.classSubMenu;
		mHandler = new Handler();
	}

	private void initAnimation() {
	}

	private void initUI() {
		// 加载滚动进入条
		mProgressBar = (ProgressBar) this.findViewById(ResFinder.getR(this,
				"R.id.progressbar_loding"));
		listView = (YXWXListView) ResFinder
				.findViewById(this, "R.id.xListView");
		layout_no_listdata = (RelativeLayout) ResFinder.findViewById(this,
				"R.id.layout_no_listdata");

		listView.setPullLoadEnable(true);
		listView.setPullRefreshEnable(true);
		listView.setXListViewListener(this);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,
					int i, long l) {
				Intent intent = new Intent(TzbMyShoucangActivity.this,
						TzbBangForumpostListActivity.class);
				intent.putExtra("FID", forumRecommend.getData()
						.get((int) l).getFid()
						+ "");
				intent.putExtra("TID", forumRecommend.getData()
						.get((int) l).getTid()
						+ "");
				intent.putExtra("Subject", forumRecommend
						.getData().get((int) l).getSubject());
				intent.putExtra("isCollected", true);
				startActivityForResult(intent, 1);
			}
		});
	}

	private void initData() {
		if (forumRecommend == null
				|| !forumRecommend.isSuccess()) {
			requestInfo();
		} else {
			initListView();
		}
	}

	private void initListView() {
		// 初始化data
		if (data == null) {
			data = new ArrayList<Map<String, Object>>();
		} else {
			data.clear();
		}
		List<ForumRecommendData> list = forumRecommend.getData();
		if (list == null || list.size() == 0) {
			layout_no_listdata.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
		} else {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				String Avatar = "";
				if (list.get(i).getAttachment() == null
						|| list.get(i).getAttachment().size() == 0) {
					Avatar = list.get(i).getUserinfo().getAvatar();
				} else {
					Avatar = list.get(i).getAttachment().get(0).getAttachment();
				}
				map.put("Avatar", Avatar);
				String subject = list.get(i).getSubject();
				if (subject != null && subject.length() >= 12) {
					subject = subject.substring(0, 12) + "…";
				}

				map.put("Subject", subject);
				String netname = list.get(i).getUserinfo().getNetname();
				if (netname == null || "".equals(netname.trim())) {
					netname = list.get(i).getUserinfo().getUsername();
				}
				// 设置几秒前、几分前、几小时前等
				String sDateline = YXWDateUtil.getTimeInterval(list.get(i).getUserinfo().getRegdate(), "MM/dd/yyyy HH:mm:ss");
				map.put("Dateline", sDateline);
				map.put("Netname", netname);
				map.put("Credits", list.get(i).getUserinfo().getCredits());
				data.add(map);
			}
			if (imageAdapter == null) {
				imageAdapter = new ImageAdapter(TzbMyShoucangActivity.this,
						data, ResFinder.getR(TzbMyShoucangActivity.this,
								"R.layout.tzb_item_tuijian"), new String[] {
								"Avatar", "Subject", "Dateline", "Netname",
								"Credits" }, new int[] {
								ResFinder.getR(TzbMyShoucangActivity.this,
										"R.id.list_item_image"),
								ResFinder.getR(TzbMyShoucangActivity.this,
										"R.id.list_item_title"),
								ResFinder.getR(TzbMyShoucangActivity.this,
										"R.id.list_item_time"),
								ResFinder.getR(TzbMyShoucangActivity.this,
										"R.id.list_item_netname"),
								ResFinder.getR(TzbMyShoucangActivity.this,
										"R.id.list_item_credits") });
				listView.setAdapter(imageAdapter);
			} else {
				imageAdapter.notifyDataSetChanged();
			}
		}
	}

	// 重载，默认请求新数据
	private void requestInfo() {
		requestInfo(TzbCommonData.NOPULL_LOAD);
	}

	private void requestInfo(int type) {
		final int type2 = type;
		if (type == TzbCommonData.NOPULL_LOAD) {
			showProgressBar();
		}
		String url = ResFinder.getResString(this,
				"R.string.tzb_url_ForumCollectList")
				+ "?oby='lastpost'"
				+ "&Page="
				+ page
				+ "&Pagesize="
				+ pagesize
				+ "&sessionid="
				+ TztData.userInfo.getData().getSessionID();
		OutLog.LogE("url", url);
		GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
		galHttpRequest.setCacheEnable(false);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<ForumRecommend>() {
				}.getType();

				forumRecommend = gson.fromJson(arg0, type);
				if (forumRecommend.isSuccess()) {
					if (type2 == TzbCommonData.PULL_LOAD_MORE) {
						int size = forumRecommend.getData().size();
						for (int i = 0; i < size; i++) {
							forumRecommend.getData().add(
									forumRecommend.getData().get(i));
						}
						if (size < 10) {
							listView.setPullLoadEnable(false);
							Toast.makeText(TzbMyShoucangActivity.this,
									"已经是最后一页！", Toast.LENGTH_LONG).show();
						}
					} else if (type2 == TzbCommonData.PULL_REFLASH
							|| type2 == TzbCommonData.NOPULL_LOAD) {
						if (forumRecommend.getData().size() < 10) {
							listView.setPullLoadEnable(false);
						} else {
							listView.setPullLoadEnable(true);
						}
					}
					initListView();
					onLoadFinish();
				} else {
					Toast.makeText(TzbMyShoucangActivity.this, "数据加载失败…",
							Toast.LENGTH_LONG).show();
				}
				removeProgressBar();
			}
		});
	}

	private void onLoadFinish() {
		listView.stopRefresh();
		listView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		listView.setRefreshTime(df.format(new Date()));
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page = 1;
				requestInfo(TzbCommonData.PULL_REFLASH);
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page++;
				requestInfo(TzbCommonData.PULL_LOAD_MORE);
			}
		}, 2000);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1){
			if (resultCode==1) {
				boolean isReflash=data.getBooleanExtra(TzbCommonData.IS_NEED_REFLASH, false);
				if(isReflash){
					requestInfo();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
